package org.doubango.ngn.h264

import com.evendai.loglibrary.Timber
import java.util.concurrent.LinkedBlockingDeque

class H264SenderThread : Thread(TAG) {
    private var mBlockingDeque: LinkedBlockingDeque<ByteArray>? = null
    private var mH264Sender: H264Sender? = null
    private var frameLossCount: Int = 0

    init {
        if (isSend) {
            mBlockingDeque = LinkedBlockingDeque(5)
            mH264Sender = H264Sender()
        }
    }

    @Suppress("SpellCheckingInspection")
    fun addH264Datas(datas: ByteArray) {
        if (isSend) {
            val offer = mBlockingDeque!!.offer(datas)
            if (!offer) {
                Timber.i("发送H264数据时丢帧：${++frameLossCount}帧")
            }
        }
    }

    override fun run() {
        try {
            while (!isInterrupted && isSend) {
                mH264Sender!!.sendH264Datas(mBlockingDeque!!.take())
            }
        } catch (e: InterruptedException) {
            Timber.w("别慌，线程是正常中断的，线程名称 = ${Thread.currentThread().name}")
        } catch (e: Exception) {
            Timber.e(e,"发送H264数据时出现异常")
        }

    }

    fun close() {
        if (isSend) {
            interrupt()
            mH264Sender!!.close()
        }
    }

    companion object {
        private val TAG = H264SenderThread::class.java.simpleName
        var isSend = false
    }
}
